/**
 * @file ext-chart.js
 *
 *
 * @copyright 2010 CloudCanvas, Inc. All rights reserved
 * @copyright 2021 Optimistik SAS, Inc. All rights reserved
 * @license MIT
 *
 */
 const name = 'barechart'
 var data = []
 const renderItem = function (params, api) {
     let categoryIndex = api.value(0)
     let start = api.coord([categoryIndex, api.value(1)])
     let end = api.coord([categoryIndex, api.value(2)])
     let width = api.size([0, api.value(2)])[0] * 0.8
     const num = api.value(4) // 每个系列柱子数
     const currentIndex = api.value(3)
     const isOdd = num % 2 === 0
     const midN = isOdd ? num / 2 : (num + 1) / 2
     var rect = ''
     width = width / num
     let rectX = start[0] - width / 2
     const FIXED_WIDTH = 0 // 柱子间距
     // 数据处理，结构为 { itemStyle: { normal: { color: 'lightgreen' } }, name: '2011', value: [0, 0, 150, 2, 5] }
     // 其中value 分为五个维度，分别为{系列项}（从0开始）、y轴起始值(均为0)、实际值、同系列中索引值（从1开始）、同系列数据项总数
     if (num > 1) {
         if (isOdd) {
             if (currentIndex <= midN) {
                 // 中位数左侧
                 rectX =
                     start[0] - width / 2 - width / 2 + (currentIndex - midN) * width - FIXED_WIDTH * (midN + 1 - currentIndex)
             } else {
                 // 中位数右侧
                 rectX =
                     start[0] - width / 2 + width / 2 + (currentIndex - midN - 1) * width + FIXED_WIDTH * (currentIndex - midN)
             }
         } else {
             rectX = start[0] - width / 2 + (currentIndex - midN) * (width + FIXED_WIDTH)
         }
     }
     rect = {
         type: 'rect',
         shape: echarts.graphic.clipRectByRect(
             { x: rectX, y: end[1], width: width, height: start[1] - end[1] },
             {
                 x: params.coordSys.x,
                 y: params.coordSys.y,
                 width: params.coordSys.width,
                 height: params.coordSys.height
             }
         ),
         style: api.style()
     }
     return rect
 }
 const pathJT = 'path://M5,20 L5,5 L8,8 L5,2 L2,8 L5,5 L5.3,6 L5.3,20'
 var option = {}
 const initOption = function () {
     option = {
         title: {
             left: 'center',
             top: 'top',
             text: "柱状图",
             textStyle: {
             }
         },
         legend: {
             left: 'center',
             data: [],
             show: false,
             top: 5,
             itemWidth: 15,
             formatter: function (name) {
                 return name;
             },
             itemHeight: 15,
         },
         grid: {
             left: 30,
             top: 30,
             bottom: 30,
             right: 30
         },
         tooltip: {
             trigger: 'item',
             show: true
         },
         xAxis: {
             axisLine: {
                 show: true,
                 symbol: ['none', 'arrow'],
                 symbolOffset: [0, 0],
                 symbolSize: [10, 15]
             },
             axisTick: {
                 show: true,
                 inside: true
             },
             splitArea: {},
             nameLocation: "center",
             type: 'category',
             data: [],
         },
 
 
         yAxis: {
             position: 'left',
             axisLine: {
                 show: true,
                 symbol: ['none', 'arrow'],
                 symbolOffset: [0, 0],
                 symbolSize: [10, 15],
             },
             type: 'value'
         },
         series: [
             {
                 type: 'custom',
                 renderItem: renderItem,
                 itemStyle: { normal: { opacity: 0.8 } },
                 encode: { y: [1, 2], x: 0 },
                 data: data,
                 label: {
                     show: true,
                     fontSize: 20,
                     position: 'top'
                 }
             }
         ]
     }
 }
 const loadExtensionTranslation = async function (svgEditor) {
      let translationModule
      const lang = svgEditor.configObj.pref('lang')
      try {
          translationModule = await import(`./locale/${lang}.js`)
      } catch (_error) {
          console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
          translationModule = await import('./locale/en.js')
      }
      svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
 }
 const initChart = function (container, option) {
     if (!option) {
         return;
     }
     $(container).empty()
     $(container).parent().attr("requiredFeatures", btoa(unescape(encodeURIComponent(JSON.stringify(option)))))
     var chart = echarts.init(container, "macarons", {
         renderer: 'svg'
     });
     chart.setOption(option);
     return chart
 }
 
 export default {
     name,
     async init() {
         const svgEditor = this
         const { svgCanvas } = svgEditor
         const { ChangeElementCommand } = svgCanvas.history
         const addToHistory = (cmd) => { svgCanvas.undoMgr.addCommandToHistory(cmd) }
         const { $id, $click, $qq, $ } = svgCanvas
         let selElems
         let started
         let newFO
         let foreignObject
         let p = {}
         let charts = new Map()
         await loadExtensionTranslation(svgEditor)
         /**
          *
          * @param {string} attr attribute to change
          * @param {string|Float} val new value
          * @returns {void}
          */
         const setAttr = (attr, val) => {
             svgCanvas.changeSelectedAttribute(attr, val)
             svgCanvas.call('changed', selElems)
         }
 
         return {
             name: svgEditor.i18next.t(`${name}:name`),
             // The callback should be used to load the DOM with the appropriate UI items
             callback() {
                 // Add the button and its handler(s)
                 // Note: the star extension needs to be loaded before the polygon extension
                 const fbtitle = `${name}:title`
                 const titleStar = `${name}:buttons.0.title`
                 const titlePolygon = `${name}:buttons.1.title`
                 const buttonTemplate = `
                 <se-button id="tool_barechart" title="${titlePolygon}" src="barechart.svg">
                 </se-button>
             `
                 svgCanvas.insertChildAtIndex($qq('.shaps .itemWrap'), buttonTemplate, 18)
 
                 $click($id('tool_barechart'), () => {
                     if (this.leftPanel.updateLeftPanel('tool_barechart')) {
                         svgCanvas.setMode('barechart')
                     }
                 })
             },
             mouseDown(opts) {
                 if (svgCanvas.getMode() === 'barechart') {
                     started = true
                     //'x', 'y', 'r1', 'r2', 'angle', 'largeArcFlag', 'sweepFlag'
                     p.x = opts.start_x
                     p.y = opts.start_y
                     var svgId = svgCanvas.getNextId()
                     newFO = svgCanvas.addSVGElementsFromJson({
                         element: 'g',
                         attr: {
                             class: 'ems echart',
                             id: svgId,
                             'doc-type': 'barechart'
                         }
                     })
 
                     foreignObject = svgCanvas.addSVGElementsFromJson({
                         element: 'foreignObject',
                         attr: {
                             x: p.x,
                             y: p.y,
                             width: 450,
                             height: 310,
                             class: 'foreignObject_bar',
                             id: "foreignObject" + svgId,
                             'font-size': 12,
                             'fill': "yellow",
                             'text-anchor': 'middle',
                             'xml:space': 'preserve',
                             'stroke': 'none',
                             'opacity': 1,
                         }
                     })
                     newFO.append(foreignObject)
                     initOption()
                     var chart = initChart(document.getElementById(`foreignObject${svgId}`), option, true)
                     charts.set(`foreignObject${svgId}`, chart)
                     return {
                         started: true
                     }
                 }
                 return undefined
             },
             mouseMove(opts) {
                 if (!started) {
                     return undefined
                 }
                 var eles = svgCanvas.getSelectedElements()
                 if (svgCanvas.getMode() === 'resize') {
                     if (eles.length == 1 && eles[0].classList.contains("echart")) {
                         var chart = charts.get("foreignObject" + eles[0].id)
                         if (chart) {
                             chart.resize()
                         }
                         return {
                             started: true
                         }
                     }
                 }
                 return undefined
             },
             mouseUp() {
                 if (svgCanvas.getMode() === 'resize' || svgCanvas.getMode() === 'select') {
                     var eles = svgCanvas.getSelectedElements()
                     if (eles.length >= 1 && eles[0].classList.contains("echart")) {
                         var chart = charts.get("foreignObject" + eles[0].id)
                         if (chart) {
                             chart.resize()
                             return {
                                 started: false
                             }
                         }
                     }
                 }
                 if (svgCanvas.getMode() === 'barechart') {
                     const keep = true
 
                     return {
                         keep,
                         element: newFO
                     }
                 }
                 return undefined
             },
             sourceChanged(opts) {
                 let elem = opts.elems[0];
                 if (!elem) return;
                 if (elem.tagName === 'svg' && elem.id === 'svgcontent') {
                     // Update svgContent (can change on import)
                     var svgContent = elem;
                     var foreignObjects = $(svgContent).find(".foreignObject_bar")
                     Array.from(foreignObjects).forEach((elem, i) => {
                         if (charts.get(elem.id) != null) {
                             charts.get(elem.id).dispose()
                             charts.delete(elem.id)
                         }
                         $(elem).removeAttr("_echarts_instance_")
                         var state = $(elem).parent().attr("requiredFeatures")
                         if (state) {
                             option = JSON.parse(decodeURIComponent(escape(atob(state))))
                             option.series[0].renderItem = renderItem
                         }
                         var chart = initChart(document.getElementById(elem.id), option, true)
                         charts.set(elem.id, chart)
                     })
                 }
             },
             updatebarechart(opts) {
                 if (opts.mode != "barechart") {
                     return
                 }
                 var eles = svgCanvas.getSelectedElements()
                 var data = opts.data
                 if (data.showTitle) {
                     option.title.text = data.title
                     option.title.textStyle.color = data.title_color
                     option.title.textStyle.fontWeight = data?.fontSetValue?.cssstyle?.["font-weight"] || null
                     option.title.textStyle.fontFamily = data?.fontSetValue?.cssstyle?.["fontfirst"] || null
                     option.title.textStyle.fontSize = data?.fontSetValue?.cssstyle?.["font-size"] || null
                     option.title.textStyle.fontStyle = data?.fontSetValue?.cssstyle?.["font-style"] || null
                 } else {
                     option.title.text = " ";
                 }
                 option.grid.borderColor = data.grid_color
                 option.grid.show = data.showGrid
                 option.grid.left = 30;
                 option.grid.top = 50;
                 option.grid.bottom = 30;
                 option.grid.right = 30;
 
 
                 option.xAxis.splitLine = { show: false, }
                 option.xAxis.axisLine.lineStyle = { color: data.zb_color, width: 1, type: 'solid' }
                 var row = data.yzb
                 option.yAxis = {
                     axisTick: { show: true, inside: true },
                     position: 'left',
                     name: row.name,
                     max: row.max,
                     nameGap: 25,
                     min: row.min,
                     splitNumber: row.num,
                     axisLine: {
                         show: true,
                         symbol: ['none', 'arrow'],
                         symbolOffset: [0, 0],
                         symbolSize: [10, 15],
                         lineStyle: { color: data.zb_color, width: 1, type: 'solid' }
                     },
                     splitLine: { show: false, },
                     type: 'value'
                 }
 
 
                 option.xAxis.axisTick = {
                     show: true,
                     inside: true
                 }
 
 
                 if (data.barGroupSet.length > 0) {
                     option.legend={};
                     option.legend.top = 'middle';
                     option.legend.show = true;
                     delete option.legend.bottom;
                     option.legend.itemWidth = '15';
                     option.legend.itemHeight = '15';
                     option.legend.data = []
                     option.xAxis.data = []
                     option.series[0].data = []
                     data.barGroupSet.forEach((row, groupIndex) => {
                         var gindex = groupIndex + 1;
                         var name = "组" + gindex;
                         if (row.barName && row.barName != "") {
                             name = row.barName;
                         }
 
                         option.xAxis.data.push(name)
                         //  option.xAxis.data.push("组" + gindex)
                         row.barSet.forEach((bar, barIndex) => {
                             var bIndex = barIndex + 1
                             var data = {
                                 itemStyle:
                                     { normal: { color: bar.bar_color } },
                                 name: `${name}${bIndex}_棒`,//此处可设置关联档案信息
                                 value: [groupIndex, 0, bar.test, bIndex, row.barNum]
                             }
                             option.series[0].data.push(data)
                             option.legend.data.push({
                                 name: data.name,
                                 icon: 'circle',
                                 // 设置文本为红色
                                 textStyle: {
                                     color: 'black',
                                     fontStyle: "15"
                                 }
                             })
                         })
                     })
                 }
                 charts.get(eles[0].firstChild.id).setOption(option, true);
                 $(eles[0]).attr("requiredFeatures", btoa(unescape(encodeURIComponent(JSON.stringify(option)))))
                 $(eles[0]).attr("state", btoa(unescape(encodeURIComponent(JSON.stringify(data)))))
                 svgEditor.layersPanel.populateObjects()
                //  addToHistory(new ChangeElementCommand(eles[0], { state: btoa(unescape(encodeURIComponent(JSON.stringify(data)))), requiredFeatures: btoa(unescape(encodeURIComponent(JSON.stringify(option)))) }))
             }
         }
     }
 }
 